<template>
    <div class="app-container">
        <div class="container-header">
            <div class="container-header-left">
                <el-form inline>
                    <!-- 表单元素 -->
                    <el-form-item>
                        <el-select v-model="room" placeholder="请选择">
                            <el-option v-for="item in rooms" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-date-picker v-model="dateTime" type="date" placeholder="请选择日期" :size="size"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- table表格：展示用户信息的地方 -->
        <el-table border stripe v-loading="listLoading" :data="users">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="avatar" label="头像" width="150">
                <template slot-scope="{ row, $index }">
                    <img :src="row.avatar || require('@/assets/image/mrtx.png')" alt="用户头像"
                        style="width: 80px; height: 80px; border-radius: 50% 50%" />
                </template>
            </el-table-column>
            <el-table-column prop="user_name" label="用户名" width="200" />
            <el-table-column prop="sex" label="性别" width="100" />
            <el-table-column prop="phone_number" label="手机号码" width="200" />
            <el-table-column prop="user_type" label="用户类型" width="150" />
            <el-table-column prop="status" label="账号状态" width="150" />
            <el-table-column prop="create_time" label="创建时间" />
            <el-table-column prop="update_time" label="更新时间">
                <template slot-scope="{ row }">
                    <div v-if="row.update_time">{{ row.update_time }}</div>
                    <div v-else>无</div>
                </template> </el-table-column>>
            <el-table-column label="操作" align="center" width="230">
                <template slot-scope="{ row }">
                    <HintButton :type="row.status == '正常' ? 'success' : 'info'" size="mini" icon="el-icon-user-solid"
                        title="修改状态" @click="showUpdateStatus(row.status, row.id)" />
                    <HintButton type="primary" size="mini" icon="el-icon-phone" title="修改手机号"
                        @click="showUpdatePhone(row)" />
                    <el-popconfirm :title="`确定删除用户 ${row.user_name} 吗?`" @confirm="removeUser(row.id)">
                        <HintButton style="margin-left: 10px" slot="reference" type="danger" size="mini"
                            icon="el-icon-delete" title="删除用户" />
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination :current-page="current" :total="total" :page-size="count" :page-sizes="[4, 10, 20, 30, 40, 50]"
            style="padding: 20px 0" layout="prev, pager, next, jumper, ->, sizes, total" @current-change="getUsers"
            @size-change="handleSizeChange" />
        <!-- 对话框的结构 -->
        <el-dialog title="添加用户" :visible.sync="dialogUserVisible">
            <el-form ref="userForm" :model="user" :rules="userRules" label-width="120px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="user.userName" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="user.password" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="user.sex" placeholder="请选择">
                        <el-option label="男" value="0"> </el-option>
                        <el-option label="女" value="1"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号码" prop="phoneNumber">
                    <el-input type="text" v-model="user.phoneNumber" />
                </el-form-item>
                <el-form-item label="用户类型" prop="userType">
                    <el-select v-model="user.userType" placeholder="请选择">
                        <el-option label="管理员" value="0"> </el-option>
                        <el-option label="普通用户" value="1"> </el-option>
                        <el-option label="微信用户" value="2"> </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button :loading="loading" type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="导入文件" :visible.sync="showImport" :before-close="importCancel">
            <div class="Import">
                <div class="download item">
                    <span class="ImportSpan">模板下载：</span>
                    <el-button type="primary" @click="download">下载 <i class="el-icon-download"></i></el-button>
                </div>
                <div class="upload item">
                    <span class="ImportSpan">数据文件：</span>
                    <div class="uploadBtn">
                        <el-upload drag action="" :http-request="modeUpload" :before-upload="beforeUploadFile"
                            ref="upload">
                            <el-button type="primary">上传 <i class="el-icon-upload2"></i></el-button>
                        </el-upload>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="importCancel">取 消</el-button>
                <el-button :loading="loading" type="primary" @click="upload">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="修改用户信息" :visible.sync="showPhoneInfo" :before-close="phoneInfoCancel">
            <el-form ref="phoneForm" :model="phoneForm" :rules="phoneRules" label-width="120px">
                <el-form-item label="当前手机号" prop="phonenumber">
                    <span>{{ phoneForm.phone_number }}</span>
                </el-form-item>
                <el-form-item label="新手机号" prop="nwePhone">
                    <el-input v-model="phoneForm.nwePhone" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="phoneInfoCancel">取 消</el-button>
                <el-button :loading="loading" type="primary" @click="phoneInfoDefine">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
//二选一
// import {
//   provinceAndCityData,
//   regionData,
//   provinceAndCityDataPlus,
//   regionDataPlus,
//   codeToText,
//   TextToCode,
// } from "element-china-area-data";
import { regionData, codeToText, TextToCode } from "element-china-area-data";

export default {
    name: "Users",
    data() {
        const checkPhone = (rule, value, callback) => {
            value = value.trim();
            let reg_tel =
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
            if (value === "") {
                callback(new Error("手机号码不能为空!"));
            } else if (!reg_tel.test(value)) {
                callback(new Error("请正确填写您的手机号码!"));
            } else {
                callback();
            }
        };
        const checkNull = (rule, value, callback) => {
            value = value.trim();
            if (value === "") {
                callback(new Error("内容不能为空!"));
            } else {
                callback();
            }
        };
        const validatePassword = (rule, value, callback) => {
            value = value.trim();
            if (value === "") {
                callback(new Error("密码长度不能为空!"));
            } else if (value.length < 6) {
                callback(new Error("密码长度不能小于6位数!"));
            } else {
                callback();
            }
        };
        return {
            dateTime: "",
            listLoading: false, // 是否显示列表加载的提示
            searchContent: "",
            searchFormFlag: false,
            users: [], // 当前页的用户列表
            importForm: [],
            current: 1, // 当前页码
            count: 4, // 每页数量
            total: 0, // 总数量
            user: {
                userName: "",
                password: "",
                sex: "",
                phoneNumber: "",
                userType: "",
            }, // 当前要操作的user
            dialogUserVisible: false, // 是否显示用户添加/修改的dialog
            showImport: false,
            currentUser: "",
            userRules: {
                // 用户添加/修改表单的校验规则
                userName: [{ validator: checkNull, trigger: "blur" }],
                phoneNumber: [{ validator: checkPhone, trigger: "blur" }],
                password: [{ validator: validatePassword, trigger: "blur" }],
                sex: [{ validator: checkNull, trigger: "blur" }],
                userType: [{ validator: checkNull, trigger: "blur" }],
            },
            phoneForm: {
                phone_number: "",
                nwePhone: "",
            },
            phoneRules: {
                nwePhone: [{ validator: checkPhone, trigger: "blur" }],
            },
            loading: false, // 是否正在提交请求中
            dialogRoleVisible: false, // 是否显示角色Dialog
            userRoleIds: [], // 用户的角色ID的列表
            isIndeterminate: false, // 是否是不确定的
            checkAll: false, // 是否全选
            mode: "",
            showPhoneInfo: false,
            modifyForm: {},
            Modifyid: "",
            // --------------
            options: regionData,
            selectedOptions: [],
        };
    },

    //发请求一般情况下，我们都是在mounted去发，但是也可以在created内部去发
    created() {
        // this.getUsers()
    },

    methods: {
        handleChange(value) {
            var loc = "";
            console.log("CodeToText", this.selectedOptions); //打印区域码
            for (let i = 0; i < this.selectedOptions.length; i++) {
                loc += codeToText[this.selectedOptions[i]];
            }
            console.log(loc);
        },
        // 获取分页列表
        async getUsers(pages = 1) {
            if (this.searchFormFlag) {
                await this.search(pages);
                return;
            }
            this.current = pages;
            const { current, count } = this;
            this.listLoading = true;
            const result = await this.$API.userList
                .reqGetUsers({ current, count })
                .catch(() => {
                    this.$message.error("获取列表失败");
                });
            console.log(result);
            this.listLoading = false;
            this.users = result.data.records.map((item) => {
                item.sex == "0" ? (item.sex = "男") : (item.sex = "女");
                item.status == "0" ? (item.status = "正常") : (item.status = "停用");
                switch (item.user_type) {
                    case "0":
                        item.user_type = "管理员";
                        break;
                    case "1":
                        item.user_type = "普通用户";
                        break;
                    default:
                        item.user_type = "微信用户";
                        break;
                }
                return item;
            });
            this.total = result.data.total;
            // const { records, total } = result.data
            // this.users = records.filter(item => item.user_name !== this.userName)
            // this.total = total - 1
            // this.selectedIds = []
        },

        // 处理pageSize发生改变的监听回调
        handleSizeChange(pageSize) {
            this.count = pageSize;
            this.getUsers();
        },

        //   根据输入进行搜索
        async search(pages) {
            if (this.searchContent.trim() == "") {
                this.searchContent = "";
                return;
            }
            console.log(typeof pages);
            if (typeof pages == "number") {
                console.log(pages);
                this.current = pages;
            } else {
                this.current = 1;
            }
            this.searchFormFlag = true;
            const { current, count } = this;
            this.listLoading = true;
            const condition = this.searchContent;
            const result = await this.$API.userList
                .reqSearchUser({ current, count, condition })
                .catch(() => {
                    this.$message.error("获取列表失败");
                });
            this.listLoading = false;
            this.users = result.data.records.map((item) => {
                item.sex == "0" ? (item.sex = "男") : (item.sex = "女");
                item.status == "0" ? (item.status = "正常") : (item.status = "停用");
                switch (item.userType) {
                    case "0":
                        item.userType = "管理员";
                        break;
                    case "1":
                        item.userType = "宿管";
                        break;
                    default:
                        item.userType = "学生";
                        break;
                }
                return item;
            });
            this.total = result.data.total;
        },
        // 清空搜索框内容清空
        resetForm() {
            if (this.searchContent == "") {
                if (this.searchFormFlag == true) {
                    this.searchFormFlag = false;
                    this.getUsers();
                }
            }
        },
        // 清空按钮清空
        resetSearch() {
            if (this.searchFormFlag == true) {
                this.searchContent = "";
                this.searchFormFlag = false;
                this.getUsers();
            } else {
                this.searchContent = "";
            }
        },
        // 批量添加
        batchAdd() {
            this.showImport = true;
            this.$nextTick(() => {
                this.$refs.upload.clearFiles();
            });
        },
        // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
        beforeUploadFile(file) {
            let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
            let size = file.size / 1024 / 1024;
            if (extension !== "xlsx") {
                this.$message.warning("只能上传后缀是.xlsx的文件");
            }
            if (size > 10) {
                this.$message.warning("文件大小不得超过10M");
            }
        },
        modeUpload(item) {
            this.mode = item.file;
        },
        // 上传
        async upload() {
            const formData = new FormData();
            formData.append("file", this.mode);
            this.loading = true;
            const result = await this.$API.userList
                .reqImportUser(formData)
                .catch(() => {
                    this.loading = false;
                    this.$message.error("上传失败");
                });
            console.log(result);
            if (result.resultCode === 200) {
                this.loading = false;
                this.$message({
                    message: result.msg,
                    type: "success",
                });
                this.showImport = false;
            } else {
                this.loading = false;
                this.$message.error("上传失败");
            }
        },
        // 下载
        async download() {
            const result = await this.$API.userList.reqDownload();
            this.exportFile(result, "user.xlsx");
        },

        exportFile(file, name) {
            let url = window.URL.createObjectURL(new Blob([file]));

            let link = document.createElement("a");

            link.style.display = "none";

            link.href = url;

            link.setAttribute("download", name);

            document.body.appendChild(link);

            link.click();

            document.body.removeChild(link); // 下载完成移除元素

            window.URL.revokeObjectURL(url); // 释放掉blob对象
        },
        async showUpdateStatus(status, id) {
            if (status == "正常") {
                const result = await this.$API.userList.reqChangeStatus({
                    status: "1",
                    id,
                });
                if (result.resultCode == 200) {
                    this.$message.success("修改成功!");
                    this.getUsers(this.current);
                } else {
                    this.$message.error("修改失败");
                }
            } else {
                const result = await this.$API.userList.reqChangeStatus({
                    status: "0",
                    id,
                });
                if (result.resultCode == 200) {
                    this.$message.success("修改成功!");
                    this.getUsers(this.current);
                } else {
                    this.$message.error("修改失败");
                }
            }
        },
        showUpdatePhone(user) {
            this.showPhoneInfo = true;
            this.phoneForm.phone_number = user.phone_number;
            this.phoneForm.id = user.id;
            this.$nextTick(() => {
                this.$refs.phoneForm.clearValidate();
            });
        },
        phoneInfoCancel() {
            this.phoneForm = {
                phone_number: "",
                nwePhone: "",
            };
            this.showPhoneInfo = false;
        },
        async phoneInfoDefine() {
            this.$refs.phoneForm.validate(async (valid) => {
                if (valid) {
                    this.loading = true;
                    this.$API.userList
                        .reqChangePhone({
                            id: this.phoneForm.id,
                            phoneNumber: this.phoneForm.nwePhone,
                        })
                        .then((res) => {
                            if (res.resultCode == 200) {
                                this.loading = false;
                                this.$message.success("修改成功!");
                                this.getUsers(this.current);
                                this.phoneForm = {
                                    phone_number: "",
                                    nwePhone: "",
                                };
                                this.showPhoneInfo = false;
                            } else {
                                this.loading = false;
                                this.$message.error("修改失败");
                            }
                        })
                        .catch(() => {
                            this.loading = false;
                            this.$message.error("修改失败");
                        });
                } else {
                    return;
                }
            });
        },
        // 删除当前用户
        async removeUser(id) {
            const result = await this.$API.userList.reqdeleteUser({ userId: id });
            if (result.resultCode == 200) {
                this.$message.success("删除成功!");
                this.getUsers(
                    this.users.length === 1 ? this.current - 1 : this.current
                );
            } else {
                this.$message.error("删除失败");
            }
            console.log(result);
        },
        /* 
              显示添加用户的界面
              */
        showAddUser() {
            this.user = {
                userName: "",
                password: "",
                sex: "",
                phoneNumber: "",
                userType: "",
            };
            this.dialogUserVisible = true;
            this.$nextTick(() => this.$refs.userForm.clearValidate());
        },
        /* 
              取消用户的保存或更新
              */
        cancel() {
            this.dialogUserVisible = false;
            this.user = {
                userName: "123",
                password: "123456",
                sex: "",
                phoneNumber: "",
                userType: "",
            };
        },
        importCancel() {
            this.showImport = false;
        },

        /* 
              保存或者更新用户
              */
        addUser() {
            this.$refs.userForm.validate(async (valid) => {
                if (valid) {
                    const user = this.user;
                    this.loading = true;
                    const result = await this.$API.userList.reqAddUsers(user);
                    console.log(result);
                    if (result.resultCode == 200) {
                        this.loading = false;
                        this.$message.success("添加成功!");
                        // this.getUsers(user.id ? this.page : 1)
                        this.getUsers(this.current);
                        this.user = {};
                        this.dialogUserVisible = false;
                    } else {
                        this.loading = false;
                        this.$message.error("添加失败");
                    }
                } else {
                    return;
                }
            });
        },
    },
    computed: {
        userName() {
            return this.$store.state.userInfo.userName || getToken("userName");
        },
    },
};
</script>

<style lang="scss" scoped>
// .el-select {
//     /deep/.el-input {
//         width: 150%;
//     }
// }
/deep/.Import {
    .item {
        margin-bottom: 5px;
        height: 44px;
        display: flex;
        align-items: center;

        .ImportSpan {
            font-size: 16px;
        }

        .uploadBtn {
            display: inline-block;
            width: 88px;
            height: 40px;
        }
    }

    // .download{

    // }
}

/deep/.el-upload-dragger {
    display: inline-block;
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 4px;
}
</style>